﻿using System.Windows;
using System.Windows.Data;
using dIRca.Data.Services;
using dIRca.Data.Settings;
using dIRca.Extras.Services;
using GalaSoft.MvvmLight.Command;
using WP7Contrib.Logging;
using WP7Contrib.Services.Navigation;
using WP7Contrib.Services.Storage;

namespace dIRca.WP7.ViewModels
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm/getstarted
    /// </para>
    /// </summary>
    public class ConnectionsViewModel : ViewModelBaseWp7
    {
        #region Commands
        private bool _canDelete;
        public bool CanDelete
        {
            get { return _canDelete; }
            set
            {
                if (_canDelete == value)
                    return;

                var oldValue = _canDelete;
                _canDelete = value;
                DeleteCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged("CanDelete", oldValue, CanDelete, true);
            }
        }

        RelayCommand _deleteCommand;
        public RelayCommand DeleteCommand
        {
            get
            {
                return _deleteCommand ?? (_deleteCommand =
                    new RelayCommand(() => this.Delete(), () => this.CanDelete));
            }
        }

        RelayCommand _screenshotCommand;
        public RelayCommand ScreenshotCommand
        {
            get
            {
                return _screenshotCommand ?? (_screenshotCommand =
                    new RelayCommand(() => this.TakeScreenshot()));
            }
        }

        RelayCommand<FrameworkElement> _layoutRootCommand;
        public RelayCommand<FrameworkElement> LayoutRootCommand
        {
            get
            {
                return _layoutRootCommand ?? (_layoutRootCommand =
                    new RelayCommand<FrameworkElement>(sender => this.LayoutRoot = sender));
            }
        }
        #endregion

        #region Properties
        private readonly ILastConnectionService _lastConnectionService;

        private string _pageTitle;
        public string PageTitle
        {
            get { return _pageTitle; }
            set
            {
                if (_pageTitle == value)
                    return;

                var oldValue = _pageTitle;
                _pageTitle = value;
                RaisePropertyChanged("PageTitle", oldValue, PageTitle, true);
            }
        }

        public CollectionViewSource Items { get; set; }

        private LastConnection _selectedItem;
        public LastConnection SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem == value)
                    return;

                var oldValue = _selectedItem;
                _selectedItem = value;
                RaisePropertyChanged("SelectedItem", oldValue, SelectedItem, true);
            }
        }

        public FrameworkElement LayoutRoot { get; private set; }
        #endregion

        /// <summary>
        /// Initializes a new instance of the ConnectionsViewModel class.
        /// </summary>
        public ConnectionsViewModel(INavigationService navigationService, ILog log, ILastConnectionService lastConnectionService)
            : base(navigationService, log)
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
            }
            else
            {
                // Code runs "for real": Connect to service, etc...
                // TODO: Always grab the active server from the ConnectionManager
                _lastConnectionService = lastConnectionService;
            }
            PageTitle = "Recent Connections";
            Items = new CollectionViewSource() { Source = _lastConnectionService.ItemsList };
            if (_lastConnectionService.ItemsList.Count > 0)
            {
                SelectedItem = Items.View.CurrentItem as LastConnection;
                CanDelete = true;
            }
        }

        void Delete()
        {
            if (Items.View.Contains(SelectedItem))
            {
                // TODO: Complain that you can't remove the only server left (which better be the active one)
                if (_lastConnectionService.ItemsList.Count <= 1)
                {
                    CanDelete = false;
                    return;
                }
                _lastConnectionService.Delete(SelectedItem);
                Items.Source = _lastConnectionService.ItemsList;
                Items.View.Refresh();
                if (_lastConnectionService.ItemsList.Count > 0)
                {
                    Items.View.MoveCurrentToLast();
                    SelectedItem = Items.View.CurrentItem as LastConnection;
                }
                else
                {
                    CanDelete = false;
                    SelectedItem = new LastConnection();
                }
            }
        }

        void TakeScreenshot()
        {
            var service = new Screenshots(LayoutRoot, App.Title + " " + PageTitle);
            service.Save();
        }

        public override void Cleanup()
        {
            // Clean own resources if needed
            base.Cleanup();
        }

        protected override void IsBeingActivated(IStorage storage)
        {
        }

        protected override void IsBeingDeactivated(IStorage storage)
        {
        }
    }
}